<template>
  <div class="container">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <!-- 搜索框组件 -->
    <van-search
      v-model.trim="keyWord"
      placeholder="请输入搜索关键词"
      shape="round"
      @search="onSearch"
    />
    <!-- 联想搜索 -->
    <van-cell-group class="suggest-box" v-if="keyWord">
      <!-- span高亮联想关键词 -->
      <van-cell icon="search" v-for="sug in suggestList" :key="sug"
        ><p
          v-html="sug"
          @click="onSearch(sug.replace(`<span>${keyWord}</span>`, keyWord))"
        ></p
      ></van-cell>
    </van-cell-group>
    <!-- 搜索历史 -->
    <div class="history-box" v-else-if="historyList.length">
      <div class="head">
        <span>历史记录</span>
        <van-icon @click="clearHistory" name="delete"></van-icon>
      </div>
      <van-cell-group>
        <van-cell v-for="history in historyList" :key="history">
          <a @click="gosearch(history)" class="word_btn">{{ history }}</a>
          <van-icon
            @click="delHistory(history)"
            class="close_btn"
            slot="right-icon"
            name="cross"
          />
        </van-cell>
      </van-cell-group>
    </div>
  </div>
</template>

<script>
import { suggest } from '../../api/article'
/**
 * 搜索历史记录 => 和后台没关系
 * 1.自己设计数据结构: ['vue3.0','今日油条']
 * 2.定义一个key
 */
// 本地存储搜索历史记录的key
// 测试mock数据
// localStorage.setItem(TOUTIAO_SEARCH_HISTORY, JSON.stringify(['vue3.0', '今日油条', '迪迦奥特曼']))
const TOUTIAO_SEARCH_HISTORY = 'TOUTIAO_SEARCH_HISTORY'
export default {
  name: 'search-index',
  data () {
    return {
      // 搜索关键词
      keyWord: '',
      // 搜索历史记录
      historyList: JSON.parse(localStorage.getItem(TOUTIAO_SEARCH_HISTORY)) || [],
      // 联想数据
      suggestList: []

    }
  },
  watch: {
    keyWord () {
      // 清除定时器异步任务
      this.timer && clearTimeout(this.timer)
      // 函数防抖：当用户停止输入后600ms后处理联想词；
      // 如果600ms内再次输入内容，会清除上一次的任务，重新计时
      // 缓存定时器=>this.timer
      this.timer = setTimeout(async () => {
        if (!this.keyWord) {
          // 为空 =>删除联想词结果
          this.suggestList = []
          return
        }
        const { status, data } = await suggest(this.keyWord)
        if (status === 200) {
          this.suggestList = data.options.map((item) => item.replace(this.keyWord, `<span>${this.keyWord}</span>`))
          // console.log(this.suggestList)
        }
      }, 600)
    }
  },
  methods: {
    // 按回车时触发
    onSearch (val) {
      // console.log(val)
      /**
       * 1.处理边界
       * 2.跳转之前 => 保存当次搜索的关键词
       * 3.带上当次的关键词 => 跳转页面
       */
      if (!val) return false
      // 处理重复
      const historySet = new Set(this.historyList)
      historySet.add(val)
      this.historyList = [...historySet]
      // 同步本地数据
      localStorage.setItem(TOUTIAO_SEARCH_HISTORY, JSON.stringify(this.historyList))
      // 跳转
      this.$router.push({ path: '/search/result', query: { q: val } })
    },
    // 删除某个历史记录
    delHistory (history) {
      // 数据删除
      this.historyList = this.historyList.filter((item) => item !== history)
      // 本地删除
      localStorage.setItem(TOUTIAO_SEARCH_HISTORY, JSON.stringify(this.historyList))
    },
    // 跳转搜索结果页 => 带上搜索关键词
    gosearch (history) {
      this.$router.push({ path: '/search/result', query: { q: history } })
    },
    // 清空历史记录
    clearHistory () {
      this.$dialog.confirm({
        title: '标题',
        message: '弹窗内容'
      })
        .then(() => {
          // console.log('确定')
          // 删除数据
          this.historyList = []
          // 删除本地
          localStorage.removeItem(TOUTIAO_SEARCH_HISTORY)
        })
        .catch(() => {
          console.log('取消')
        })
    }
  }
}
</script>

<style scoped lang='less'>
// 联想搜索
.suggest-box {
  /deep/ .van-cell {
    padding: 10px 20px;
    color: #999;
    p {
      span {
        color: red;
      }
    }
  }
}
// 搜索记录
.history-box {
  padding: 0 20px;
  .head {
    line-height: 36px;
    color: #999;
    .van-icon {
      font-size: 16px;
      float: right;
      margin-top: 10px;
    }
  }
  .van-cell {
    padding: 10px 0;
  }
  .word_btn {
    color: #3296fa;
  }
  .close_btn {
    margin-top: 5px;
    color: #999;
  }
}
</style>
